package com.brotherly.util.downloader;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.brotherly.framework.app.BaseApplication;

/**
 * 
 * 一个业务类
 */
public class DBUtil
{
    private DBHelper dbHelper;

    private static DBUtil Instance = new DBUtil(BaseApplication.getInstance());

    private DBUtil(Context context)
    {
        dbHelper = new DBHelper(context);
    }

    public static DBUtil getInstance()
    {
        return Instance;
    }

    /**
     * 查看数据库中是否有未完成数据
     */
    public synchronized boolean isHasInfors(String urlstr)
    {
        Cursor cursor = null;
        SQLiteDatabase database = null;
        int count = 0;
        try
        {
            database = dbHelper.getReadableDatabase();
            String sql = "select count(*)  from download_info where url=? and complete = 0";
            cursor = database.rawQuery(sql, new String[]
            {
                    urlstr
            });
            cursor.moveToFirst();
            count = cursor.getInt(0);
        }
        catch (Exception e)
        {
            Log.e("mpgp", e.getLocalizedMessage());
        }
        finally
        {
            try
            {
                cursor.close();
                database.close();
            }
            catch (Exception e)
            {}
        }
        return count == 0;
    }

    /**
     * 
     * @return 未下载完成的URL
     */
    public synchronized DownloadInfo[] getAllInfo()
    {
        Cursor cursor = null;
        DownloadInfo[] infos = null;
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            String sql = "select  thread_id, start_pos, end_pos,compelete_size,url,filename,complete  from download_info where exists = 0 ";
            cursor = database.rawQuery(sql, null);
            infos = new DownloadInfo[cursor.getCount()];
            int index = 0;
            while (cursor.moveToNext())
            {
                DownloadInfo info = new DownloadInfo(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
                        cursor.getString(4), cursor.getString(5), cursor.getInt(6));

                infos[index] = info;
                index++;
            }
        }
        catch (Exception e)
        {
            Log.d("mpgp", e.getLocalizedMessage());
        }
        finally
        {
            try
            {
                cursor.close();
                database.close();
            }
            catch (Exception e)
            {}
        }
        return infos;
    }

    /**
     * 保存 下载的具体信息
     */
    public synchronized void saveInfos(List<DownloadInfo> infos)
    {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        try
        {
            for (DownloadInfo info : infos)
            {
                String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url,filename,complete) values (?,?,?,?,?,?,0)";
                Object[] bindArgs =
                {
                        info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl(),
                        info.getFileName()
                };
                database.execSQL(sql, bindArgs);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            database.close();
        }
    }

    /**
     * 得到下载具体信息
     */
    public synchronized List<DownloadInfo> getInfos(String urlstr)
    {
        Cursor cursor = null;
        List<DownloadInfo> list = new ArrayList<DownloadInfo>();
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            String sql = "select thread_id, start_pos, end_pos,compelete_size,url,filename,complete from download_info where url=? ";
            cursor = database.rawQuery(sql, new String[]
            {
                    urlstr
            });
            while (cursor.moveToNext())
            {
                DownloadInfo info = new DownloadInfo(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
                        cursor.getString(4), cursor.getString(5), cursor.getInt(6));
                list.add(info);
            }
        }
        catch (Exception e)
        {
            Log.e("mpgp", e.getLocalizedMessage());
        }
        finally
        {
            try
            {
                cursor.close();
                database.close();
            }
            catch (Exception e)
            {

            }
        }
        return list;
    }

    /**
     * 更新数据库中的下载信息
     */
    public synchronized void updataInfos(int threadId, int filesize, int compeleteSize, String urlstr)
    {
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            String sql = "update download_info set end_pos=?, compelete_size=? where thread_id=? and url=?  ";
            Object[] bindArgs =
            {
                    filesize, compeleteSize, threadId, urlstr
            };
            database.execSQL(sql, bindArgs);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                database.close();
            }
            catch (Exception e)
            {

            }
        }
    }

    /**
     * 关闭数据库
     */
    public void closeDb()
    {
        dbHelper.close();
    }

    /**
     * 下载完成后,修改状态
     */
    public synchronized void updateComplete(String url)
    {
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            String sql = "update download_info set complete=1 where  url=?  ";
            Object[] bindArgs =
            {
                    url
            };
            database.execSQL(sql, bindArgs);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                database.close();
            }
            catch (Exception e)
            {

            }
        }
    }

    /**
     * 清楚全部数据
     */
    public synchronized void deleteByUrl(String url)
    {
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            database.delete("download_info", "url=?", new String[]
            {
                    url
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                database.close();
            }
            catch (Exception e)
            {

            }
        }
    }

    /**
     * 清除全部数据
     */
    public synchronized void deleteAll()
    {
        SQLiteDatabase database = null;
        try
        {
            database = dbHelper.getReadableDatabase();
            database.delete("download_info", "", null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                database.close();
            }
            catch (Exception e)
            {

            }
        }
    }
}
